package com.servlet.teacher;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.util.JsonUtil;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;


/**
 *  此类根据客户端传递过来的method参数，动态调用继承该类的子类中的方法
 *  子类的方法参数，返回类型和方法抛出异常应该和doGet类似,子类的方法的修饰符应该是public的
 *  特别注意：继承该类的子类不要重写doGet方法
 */
public class BaseServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("xxxxxxxxxxxxxxxxxxxxxxxxx");
        HttpSession httpSession = req.getSession();//得到为每个客户端分别一个sesison对象
        System.out.println("为客户端分别的sessionId为:"+httpSession.getId());

        resp.setContentType("text/html;charset=utf-8");

        String method = req.getParameter("method");//参数method应该是要调用的方法名称
        //判断method是否为空或空字符串，如果是，则直接返回一段错误信息

        GsonBuilder gsonBuilder = new GsonBuilder();
        Gson gson = gsonBuilder.create();
        PrintWriter out = resp.getWriter();
        JsonUtil jsonUtil = new JsonUtil();

        if (method!=null && !method.equals("")){
                //利用反射来调用子类自定义的方法

            //如果method=delete,则需要得到一个   delete(HttpServletRequest req, HttpServletResponse resp) 方法所对应Mehod对象
            try {
                Method m = this.getClass().getDeclaredMethod(method,HttpServletRequest.class,HttpServletResponse.class);
                m.invoke(this,req,resp);
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
                jsonUtil.setCode(1);
                jsonUtil.setMsg("根据您传递的参数"+method+"在 "+this.getClass().getName()+"中找不到相应的方法");
                out.print(gson.toJson(jsonUtil));
            } catch (IllegalAccessException e) {
                e.printStackTrace();
                jsonUtil.setCode(1);
                jsonUtil.setMsg("根据您传递的参数"+method+"无法调用"+this.getClass().getName()+"类中方法，请检查该方法是否为public修饰的");
                out.print(gson.toJson(jsonUtil));
            } catch (InvocationTargetException e) {
                e.printStackTrace();
                jsonUtil.setCode(1);
                jsonUtil.setMsg("根据您传递的参数method"+method+"调用"+this.getClass().getName()+"类该方法出现了异常"+e.getMessage());
                out.print(gson.toJson(jsonUtil));
            }

        }else {

            jsonUtil.setCode(1);
            jsonUtil.setMsg("请求参数中未包含method的，请检查");

            out.print(gson.toJson(jsonUtil));
        }


    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req,resp);
    }
}
